package com.jas.storage;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.jas.common.DeadlineEvent;
import com.jas.common.Event;
import com.jas.common.FloatingEvent;
import com.jas.common.TimedEvent;

public class EventDeserializer implements JsonDeserializer<List<Event>> {

	//@author a0118677r
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public List<Event> deserialize(JsonElement jsonElement, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {

        List list = new ArrayList<Event>();
        JsonArray jasonArray = jsonElement.getAsJsonArray();

        for (JsonElement je : jasonArray) {
        	
        	Class eventSubClass;
            switch(je.getAsJsonObject().get("CLASS_NAME").getAsString()){
            case "DeadlineEvent":
            	eventSubClass = DeadlineEvent.class;
            	break;
            case "FloatingEvent":
            	eventSubClass = FloatingEvent.class;
            	break;
            case "TimedEvent":
            	eventSubClass = TimedEvent.class;
            	break;
            default:
            	throw new RuntimeException("Unknown class: " + je.getAsJsonObject().get("CLASS_NAME").getAsString());
            }
            
        	list.add(context.deserialize(je, eventSubClass));
        }

        return list;

    }

}
